package com.power.sifa.correction.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.correction.dao.Crc_group_personDao;
import com.power.sifa.correction.model.Crc_group_person;
import com.power.sifa.correction.service.Crc_group_personService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.power.sifa.correction.model.Crc_group;
import com.power.sifa.correction.dao.Crc_groupDao;
import com.power.sifa.correction.service.Crc_groupService;
import com.power.sifa.correction.model.pageInfo.Crc_groupPageInfo;

import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  社区矫正人员分组信息业务层实现
 */
@Service
public class Crc_groupServiceImpl extends BaseServiceImpl implements Crc_groupService {

    @Autowired
    private Crc_groupDao dao;

    @Autowired
    private Crc_group_personDao crc_group_personDao;

    @Autowired
    private Crc_group_personService crc_group_personService;

    @Override
    public Crc_group getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Crc_group crc_group) {
        // 关联关系新增
        List<String> personIds = crc_group.getPersonIds();
        if (CollectionUtil.isNotEmpty(personIds)) {
           List<Crc_group_person> group_personList = new ArrayList<>();
           personIds.stream().forEach(element -> {
               Crc_group_person group_person = new Crc_group_person();
               group_person.setId(NanoIdUtils.randomNanoId());
               group_person.setPerid(element);
               group_person.setGrpid(crc_group.getId());
               group_personList.add(group_person);
           });
           if (CollectionUtil.isNotEmpty(group_personList)) {
               // 删除之前的分组下的关联的社矫人员
               this.crc_group_personService.removeByGroupId(crc_group.getId());
               this.crc_group_personService.saveAll(group_personList);
           }
        } else {
            // 为空则删除当前的关联人员
            this.crc_group_personService.removeByGroupId(crc_group.getId());
        }
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (crc_group.getPrimaryKey() != null) {
        	 Crc_group crc_groupfDb = dao.findById(crc_group.getPrimaryKey()).orElse(null);
             if(crc_groupfDb != null) {
                BeanUtils.copyProperties(crc_group, crc_groupfDb);
                 crc_groupfDb.setDeleted(0);
                dao.save(crc_groupfDb);
                return;
             }
        }
        crc_group.setDeleted(0);
        dao.save(crc_group);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String id) {
        // 删除当前的分组信息
        List<String> ids = new ArrayList<>();
        ids.add(id);
        dao.removeByIds(ids);
        // 删除当前的分组记录人员信息
        crc_group_personService.removeByGroupId(id);
    }

    @Override
    public Page<Crc_group> findAll(Crc_groupPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        // 默认查询删除标志为0的数据
        pageInfo.setF_deleted(0);
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<String> ids) {
        dao.removeByIds(ids);
    }
    
    @Override
	public List<Crc_group> findAll() {
        // 默认查询删除标志为0的数据
        Specification<Crc_group> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.equal(root.get("deleted"), 0)
        ).getRestriction();
        return dao.findAll(specification);
	}
	
	@Override
	public void saveAll(List<Crc_group> list) {
        list.stream().forEach(element -> {
            element.setDeleted(0);
        });
		dao.saveAll(list);
	}

    @Override
    public List<Crc_group> findByGroupIds(List<String> groupIds) {
        return dao.findByGroupIds(groupIds);
    }


    @Override
    public List<Crc_group> findGroupByPersonId(String personId) {
        List<String> personIds = new ArrayList<>();
        personIds.add(personId);
        Map<String, List<Crc_group>> groupMap = this.findGroupByPersonIds(personIds);
        return groupMap.get(personId);
    }

    @Override
    public Map<String, List<Crc_group>> findGroupByPersonIds(List<String> personIds) {
        Map<String, List<Crc_group>> result = new HashMap<>();
        if (CollectionUtil.isNotEmpty(personIds)) {
            List<Crc_group_person> group_personList = this.crc_group_personDao.findByPersonIds(personIds);
            if (CollectionUtil.isNotEmpty(group_personList)) {
                List<String> groupIds = group_personList.stream().map(Crc_group_person::getGrpid).distinct().collect(Collectors.toList());
                List<Crc_group> groupList = this.findByGroupIds(groupIds);
                // 构建返回的map
                Map<String, List<Crc_group_person>> group_personMapList = group_personList.stream().collect(Collectors.groupingBy(Crc_group_person::getPerid));
                for (String personId: group_personMapList.keySet() ) {
                    List<String> innerGroupIds = group_personMapList.get(personId).stream().map(Crc_group_person::getGrpid).collect(Collectors.toList());
                    List<Crc_group> fileGroupList = groupList.stream().filter(element -> CollectionUtil.isNotEmpty(innerGroupIds) && innerGroupIds.contains(element.getId())).collect(Collectors.toList());
                    result.put(personId, fileGroupList);
                }
            }
        }
        return result;
    }

}
